package com.qyy.remotemonitor.common.mvp;

import android.content.Context;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.qyy.remotemonitor.http.base.BaseRequestParam;
import com.wang.android.library.di.EasyBasePresenter;
import com.wang.android.library.ui.IFBaseView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * Created by WangHuanyu on 2018/1/2.
 */

public class BasePresenter<V extends IFBaseView> implements EasyBasePresenter<V>
{
    protected Context context;
    private V view;
    protected CompositeDisposable mCompositeDisposable;

    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    protected void addSubscribe(Disposable subscription) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }

    @Override
    public void attachView(V view) {
        //TODO 绑定view
        this.view = view;
    }

    public V getView() {
        return view;
    }

    @Override
    public void detachView() {
        this.view = null;
        unSubscribe();
    }

    public void onDestory(){};

    @Override
    public void setContext(Context context) {
        this.context = context;
    }

    /**
     * 校验data为null时抛出异常类型
     * @param e
     * @return
     */
    public boolean checkData(Throwable e)
    {
        return false;
    }

 /*   *
     *  将
     * @param param
     * @return
     */
    public RequestBody convertPostBody(BaseRequestParam param)
    {
        Gson gson=new Gson();
        String route= gson.toJson(param);
        try {
            route = URLDecoder.decode(route, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=UTF-8"),route);
        LogUtils.d("netInfo"," post body is :" + route);
        return body;
    }
}
